import { SchemaManage } from '@/components/SchemaComponent';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { AcceptanceManageAPI } from '../common/type';
import { AcceptanceManageContext, getTableColumns } from '../mconfig';
import { PlusOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { getKeyRouter, getTenantID } from '@/utils';
import { cancelAssetMaterielService } from '../services';
import moment from 'moment';
import { ILoadMapTypeAll } from '@/common';
import { message } from 'antd';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { UploadModal } from './UploadModal';

export const ManageRightTableView: React.FC<AcceptanceManageAPI.IManageTableView> = ({ searchRenderID }) => {
  const designManageTableRef: any = React.useRef();

  /**
   * 获取上下文
   */
  const {
    leftSelectName,
    rightTableProps: { dataSource, loading, getAcceptanceTableData, pagination, otherParams, searchList, reloadTableData },
    leftSelectKeys,
    curRes,
    typeSelectRow,
  } = useContext(AcceptanceManageContext);

  /**
   * 表格默认 参数
   */
  const tableParams = useMemo(() => {
    return {
      orderType: typeSelectRow?.orderType,
      tableName: typeSelectRow?.tableName,
      dicTypeIds: typeSelectRow?.orderType?.substring(0, 8),
    };
  }, [typeSelectRow]);

  /** 失效提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null,
  });
  /** 批量上传弹窗 */
  const [isShowBatch, setIsShowBatch] = useState<boolean>(false);

  /**
   * 监听 左侧树节点选中 改变
   */
  useEffect(() => {
    if (leftSelectKeys && leftSelectKeys?.length > 0) {
      let tablePayload = {
        ...otherParams,
        ...tableParams,
        assetStoreId: leftSelectKeys[0],
      };
      getAcceptanceTableData({ ...tablePayload });
    }
  }, [leftSelectKeys]);

  /** 切换方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    if (key) {
      getAcceptanceTableData({ ...params, ...searchValues });
    }
  };

  /**
   * 重置搜索表单方法
   */
  const onReset = (values: any) => {
    getAcceptanceTableData({ ...tableParams, ...values });
  };

  /**
   * 搜索列表
   */
  const onSearch = (request: AcceptanceManageAPI.IGridRequestType) => {
    getAcceptanceTableData({ ...otherParams, ...request });
  };

  /**
   * 分页change 方法
   */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getAcceptanceTableData({ ...otherParams, pageSize, current, ...params });
  };

  /** 管理页面头部操作集合 */
  const tableActionList: AcceptanceManageAPI.IHeaderActionType = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/assetMaterial/add'] ?? false,
        // visible: true,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          history.push({
            pathname: `/assetMaterial/add/:${getKeyRouter()}${getKeyRouter()}`,
            state: {
              pageType: 'add',
              leftSelectName: leftSelectName,
              leftSelectKeys: leftSelectKeys,
            },
          });
        },
      },
      {
        title: '导入',
        visible: true,
        type: 'primary',
        icon: <DownloadOutlined />,
        onClick: () => {
          setIsShowBatch(true);
        },
      },
    ];
  }, [curRes, leftSelectName]);

  /** 作废回调 */
  const updateCallback = (res: any, clickType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadTableData();
    } else {
      message.error(res?.msg);
    }
  };
  /** 作废按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };
  /** 作废接口 */
  const { cancelAssetMaterielLoading, cancelAssetMaterielRun } = cancelAssetMaterielService(updateCallback);

  /** Table操作列的事件池 */
  const getTableOperateFuncs: AcceptanceManageAPI.IMaterialTableActionType = {
    /** 编辑按钮 */
    onEdit(record) {
      let obj = JSON.parse(JSON.stringify(record));
      let objectKeysArr = Object.keys(obj.assetjson);
      let filterArr = objectKeysArr.filter((item: string) => {
        return item.substring(item.length - 4) === 'Date';
      });
      for (let i = 0; i < filterArr.length; i++) {
        obj.assetjson[filterArr[i]] = obj.assetjson[filterArr[i]] ? moment(obj.assetjson[filterArr[i]]) : '';
      }
      obj.assetjson.hasOwnProperty('warrantyDeadline') &&
        (obj.assetjson.warrantyDeadline = obj.assetjson.warrantyDeadline ? moment(obj.assetjson.warrantyDeadline) : '');
      history.push({
        pathname: `/assetMaterial/edit/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          pageType: 'edit',
          record: obj,
        },
      });
    },
    /** 失效按钮 */
    onCancel(record) {
      setOpenTipInfoModal({
        checkRowObj: record,
        showModal: true,
        tipType: 'delete',
      });
    },
  };

  /**Table的columns集合*/
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, getTableOperateFuncs, leftSelectName);
  }, [curRes, leftSelectName]);

  return (
    <>
      <SchemaManage
        ref={designManageTableRef}
        searchProps={{
          switchList: [], //头部切换列表
          searchList, //搜索表单列表
          onReset, //重置
          onSwitch, //头部切换
          onSearch, //搜索方法
        }}
        actionList={tableActionList} //Table头部操作按钮列表
        searchDrawerRender={searchRenderID}
        tableProps={{
          // table 表格属性
          columns,
          dataSource,
          loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange, //分页change方法
        }}
      />
      {/* 提示框 */}
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          // ref={tipErrorModalRef}
          modalLoading={cancelAssetMaterielLoading}
          onClose={tipOnClose}
          modalOnOK={() => {
            let obj = {
              id: openTipInfoModal.checkRowObj.id,
              assetState: `${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}1003`,
            };
            cancelAssetMaterielRun(obj);
          }}
          modalTip={'确认改为失效状态，失效后不可恢复！'}
          tipTextColor="#000"
        />
      )}
      {isShowBatch && (
        <UploadModal
          onClose={() => {
            setIsShowBatch(false);
          }}
          reloadManage={reloadTableData}
          curRes={curRes}
        />
      )}
    </>
  );
};
